package com.wonders.module.auth.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wonders.common.constant.CommonConstant;
import com.wonders.framework.util.bean.BeanUtil;
import com.wonders.module.auth.constant.AuthConstant;
import com.wonders.module.auth.dao.MenuDao;
import com.wonders.module.auth.dao.RoleAuthDao;
import com.wonders.module.auth.entity.bo.RoleAuth;
import com.wonders.module.auth.entity.vo.MenuVo;
import com.wonders.module.auth.entity.vo.RoleAuthVo;
import com.wonders.module.auth.service.RoleAuthService;

/**
 * 角色权限业务层实现
 * 
 * @author WuBin
 * 
 */
@Service
public class RoleAuthServiceImpl implements RoleAuthService {

	@Autowired
	private MenuDao menuDao;

	@Autowired
	private RoleAuthDao roleAuthDao;

	public List<MenuVo> queryRoleMenu(RoleAuthVo roleAuthVo) {
		MenuVo sMenuVo = new MenuVo();
		sMenuVo.setEnable(CommonConstant.Status.ENABLED);
		List<MenuVo> menuList = BeanUtil.copyList(menuDao.query(sMenuVo),
				MenuVo.class);
		List<RoleAuth> roleAuthList = roleAuthDao.query(roleAuthVo);
		Map<Long, String> roleAuthMap = new HashMap<Long, String>();
		for (RoleAuth roleAuth : roleAuthList) {
			roleAuthMap.put(roleAuth.getAuthId(), "");
		}
		for (MenuVo menuVo : menuList) {
			if (roleAuthMap.get(menuVo.getId()) != null) {
				menuVo.setChecked(true);
			}
		}
		return menuList;
	}

	public void saveRoleMenu(Long roleId, List<Long> keys) {
		RoleAuthVo roleAuthVo = new RoleAuthVo();
		roleAuthVo.setRoleId(roleId);
		roleAuthVo.setAuthType(AuthConstant.AuthType.MENU);
		roleAuthDao.remove(roleAuthVo);
		for (Long key : keys) {
			RoleAuth roleAuth = new RoleAuth();
			roleAuth.setAuthId(key);
			roleAuth.setAuthType(AuthConstant.AuthType.MENU);
			roleAuth.setRoleId(roleId);
			roleAuthDao.save(roleAuth);
		}
	}

}
